<template>
  <div>
    <el-form ref="formRef" :model="state.ruleForm" size="large" class="login-content-form">
      <div class="login-title">
        <span class="login-title-showy">{{ getDescByValue(CEAccountType, state.ruleForm.accountType as string) }}密码</span>登录
      </div>
      <el-form-item
        v-if="state.ruleForm.accountType == CEAccountType.Account.value"
        class="login-animation1"
        prop="userName"
        :rules="[{ required: true, message: '请输入账号', trigger: ['blur', 'change'] }]"
      >
        <el-input
          text
          :placeholder="'请输入账号'"
          v-model="state.ruleForm.userName"
          clearable
          autocomplete="off"
          @keyup.enter="onSignIn"
        >
          <template #prefix>
            <EleIcon name="user"/>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="state.ruleForm.accountType == CEAccountType.Mobile.value"
        class="login-animation1"
        prop="mobile"
        :rules="[
          { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
          { validator: validatorCustom('mobile'), trigger: ['blur', 'change'] },
        ]"
      >
        <el-input
          ref="phoneRef"
          text
          :placeholder="'请输入手机号'"
          maxlength="11"
          v-model="state.ruleForm.mobile"
          clearable
          autocomplete="off"
          @keyup.enter="onSignIn"
        >
          <template #prefix>
            <EleIcon name="iphone"/>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="state.ruleForm.accountType == CEAccountType.Email.value"
        class="login-animation1"
        prop="email"
        :rules="[
          { required: true, message: '请输入邮箱地址', trigger: ['blur', 'change'] },
          { validator: validatorCustom('email'), trigger: ['blur', 'change'] },
        ]"
      >
        <el-input
          ref="emailRef"
          text
          :placeholder="'请输入邮箱地址'"
          v-model="state.ruleForm.email"
          clearable
          autocomplete="off"
          @keyup.enter="onSignIn"
        >
          <template #prefix>
            <EleIcon name="promotion"/>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="login-animation2" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]">
        <el-input
          :placeholder="'请输入密码'"
          v-model="state.ruleForm.password"
          show-password
          autocomplete="off"
          @keyup.enter="onSignIn"
        >
          <template #prefix>
            <EleIcon name="unlock"/>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="login-animation4 mb12">
        <el-button
          type="primary"
          class="login-content-submit"
          round
          @click="onSignIn"
          :disabled="state.disabled.signIn"
          :loading="state.loading.signIn"
        >
          <span>登 录</span>
        </el-button>
      </el-form-item>
      <div
        class="login-animation4 my-flex f12 mt10"
        :class="state.ruleForm.accountType == CEAccountType.Account.value ? 'my-flex-end' : 'my-flex-between'"
      >
        <el-link
          v-if="state.ruleForm.accountType == CEAccountType.Mobile.value"
          :underline="false"
          type="primary"
          class="f12"
          @click="loginComponentName = CEComponentType.Mobile.name"
          >手机验证码登录</el-link>
        <el-link
          v-if="state.ruleForm.accountType == CEAccountType.Email.value"
          :underline="false"
          type="primary"
          class="f12"
          @click="loginComponentName = CEComponentType.Email.name"
          >邮箱验证码登录</el-link>
        <el-link v-if="isShowForgotPassword" :underline="false" type="primary" class="f12" @click="onForgotPassword">忘记密码</el-link>
      </div>
    </el-form>
    <CaptchaDialog ref="captchaDialogRef" v-model="state.showDialog" @ok="onOk" />
  </div>
</template>

<script setup lang="ts" name="loginAccount">
import { reactive, computed, ref, defineAsyncComponent, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { Session } from '@/core/storage'
import { formatAxis } from '@/core/helpers/formatTime'
import { NextLoading } from '@/core/helpers/loading'
import { cloneDeep } from 'lodash-es'
import { validatorCustom } from '@/core/validators'
import { getDescByValue } from '@/core/helpers/enum'
import type { TAccountType,IAuthLoginInput } from '@/core/api/types-contracts'
import { EAccountType,  } from '@/core/api/types-contracts'
import { CEAccountType, CEComponentType } from '@/core/api/enum-contracts'

const props = defineProps({
  isShowForgotPassword: {
    type: Boolean,
    default: true,
  },
});


const CaptchaDialog = defineAsyncComponent(() => import('@/app/components/captcha/dialog.vue'))
const EleIcon = defineAsyncComponent(() => import('@/app/components/icons/index.vue'))
const loginComponentName = defineModel('loginComponentName', { type: String })
const accountType = defineModel('accountType', { type: String, default: EAccountType.Account})
const isChangePassword = defineModel('isChangePassword', { type: Boolean, default: false })
const changePasswordComponentName = defineModel('changePasswordComponentName', { type: String })

// 定义变量内容
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const formRef = ref()
const captchaDialogRef = ref()

const state = reactive({
  showDialog: false,
  ruleForm: {
    userName: '',
    mobile: '',
    email: '',
    accountType: accountType.value,
    password: '',
    captchaId: '',
    captchaData: '',
  } as IAuthLoginInput,
  loading: {
    signIn: false,
  },
  disabled: {
    signIn: false,
  },
})

// 时间获取
const currentTime = computed(() => {
  return formatAxis(new Date())
})

//忘记密码
const onForgotPassword = () => {
  if (state.ruleForm.accountType == CEAccountType.Email.value) changePasswordComponentName.value = CEComponentType.Email.name
  else if (state.ruleForm.accountType == CEAccountType.Mobile.value) changePasswordComponentName.value = CEComponentType.Mobile.name
  isChangePassword.value = true
}

//验证通过
const onOk = (data: any) => {
  state.showDialog = false
  //开始登录
  state.ruleForm.captchaId = data.captchaId
  state.ruleForm.captchaData = JSON.stringify(data.track)
  login()
}

//登录
const login = async () => {
  state.loading.signIn = true
  const loginForm = cloneDeep(state.ruleForm)
  //TODO 登陆
  signInSuccess(true)
}

// 点击登录
const onSignIn = async () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    //检查是否开启验证码登录
    state.disabled.signIn = true
    
    //TODO 这里些登录代码

  })
}
// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
  if (isNoPower) {
    ElMessage.warning('抱歉，您没有分配权限，请联系管理员')
    //移除
    Session.clear()
  } else {
    // 初始化登录成功时间问候语
    let currentTimeInfo = currentTime.value
    // 登录成功，跳到转首页
    // 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
    if (route.query?.redirect) {
      router.push({
        path: <string>route.query?.redirect,
        query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
      })
    } else {
      router.push('/')
    }
    // 登录成功提示
    const signInText = t('message.signInText')
    ElMessage.success(`${currentTimeInfo}，${signInText}`)
    // 添加 loading，防止第一次进入界面时出现短暂空白
    NextLoading.start()
  }
  state.loading.signIn = false
}

watchEffect(() => {
  state.ruleForm.accountType = accountType.value as TAccountType
})
</script>

<style scoped lang="scss">
@import './login.scss';
</style>
